<template>
  <view>
	  <view class="u-demo-block__content" style="margin: 16rpx; display: flex; align-items: center;">
		<text style="margin-right: 7rpx;">入库日期：</text>
	  	<view class="u-page__tag-item" style="flex: 1;">
			  <uni-datetime-picker 
			  v-model="pickedDateRange" 
			  type="daterange" 
			  @change="dateRangeClick" />
	  	</view>
	  </view>
	  <view class="mobile-item-container">
		<uni-section :title="`入库纪录(合同:${contractCode}) `" type="line">
		</uni-section>
		<view v-if="pickedMainList.length === 0">
			<u-empty mode="data"></u-empty>
		</view>
		<view v-else>
			<uni-collapse accordion v-model="accordionVal" @change="change">
				<uni-collapse-item :thumb="item.thumb" :title="item.mainText" v-for="(item, index) in pickedMainList" :key="index" >
					<uni-section :title="`入库单`" type="line"></uni-section>
					<view v-if="failedBillBoList.length > 0">
						<view style="margin-top: 0px;">
							<uni-table ref="table" :loading="detailLoading"
								border
								stripe 
								type="" 
								emptyText="暂无更多数据">
							<uni-tr style="background-color: #dbfbdb;">
								<uni-th align="left" width="5" style="font-size: 12px;color: #62c188;">序号</uni-th>
								<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">入库单号</uni-th>
								<uni-th align="left" width="70" style="font-size: 12px;color: #62c188;">领料状态</uni-th>
								<uni-th align="left" style="font-size: 12px;color: #62c188;">失败原因</uni-th>
							</uni-tr>
							<uni-tr v-for="(subItem, index) in failedBillBoList" :key="index" style="height: 40px;">
								<uni-td align="left" style="font-size: 12px;text-align: left;">{{ index+1 }}</uni-td>
								<uni-td align="left" style="font-size: 12px;text-align: left;">{{ subItem.billNo }}</uni-td>
								<uni-td align="left">{{subItem.statusDesc}}</uni-td>
								<uni-td align="left" style="font-size: 12px;text-align: left;">{{ subItem.errorMessage }}</uni-td>
							</uni-tr>
							</uni-table>
						</view>
					</view>
					
				
					<!-- 产品列表（主表） -->
					<uni-section :title="`产品列表`" type="line"></uni-section>
					<view style="margin-top: 0px;">
						<uni-table ref="table" :loading="detailLoading"
							border
							stripe 
							type="" 
							emptyText="暂无更多数据">
						<uni-tr style="background-color: #dbfbdb;">
							<uni-th align="left" width="5" style="font-size: 12px;color: #62c188;">序号</uni-th>
							<!-- <uni-th align="left" width="40" style="font-size: 12px;color: #62c188;">产品编码</uni-th> -->
							<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">物料编码</uni-th>
							<uni-th align="left" width="80" style="font-size: 12px;color: #62c188;">物料名称</uni-th>
							<uni-th align="left" width="80" style="font-size: 12px;color: #62c188;">物料规格</uni-th>
							<uni-th align="left" width="130" style="font-size: 12px;color: #62c188;">入库仓库</uni-th>
							<uni-th align="left" width="130" style="font-size: 12px;color: #62c188;">批号</uni-th>
							<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">生产数量</uni-th>
							<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">实收数量</uni-th>
							<uni-th align="left" width="150" style="font-size: 12px;color: #62c188;">备注</uni-th>
						</uni-tr>
						<uni-tr v-for="(subItem, index) in allSubMaterialList" :key="index">
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ index+1 }}</uni-td>
							<!-- <uni-td align="left" style="font-size: 12px;text-align: left;">{{ subItem.productCode }}</uni-td> -->
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ subItem.bomCode }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ subItem.bomName }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ subItem.bomStandard }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ subItem.stockNumber }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ subItem.lot }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ subItem.needQty }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ subItem.pickedItemQty }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ subItem.remark }}</uni-td>
						</uni-tr>
						</uni-table>
					</view>
				</uni-collapse-item>
			</uni-collapse>
		</view>
		
		<uni-fab ref="fab" 
			:pattern="pattern" 
			:content="content" 
			:horizontal="horizontal" 
			:vertical="vertical"
			:direction="direction" 
			@trigger="trigger" 
			@fabClick="fabClick" />
			
		<u-modal
			:content="resendContent"
			:show="submitResendShow"
			showCancelButton
			closeOnClickOverlay
			@confirm="submitResend"
			@cancel="() => submitResendShow = false"
		></u-modal>
		<u-toast ref="uToast" duration="3000" />
	  </view>
  </view>
</template>

<script>
const d = new Date();
const year = d.getFullYear();
let month = d.getMonth() + 1;
month = month < 10 ? `0${month}` : month;
const date = d.getDate();

import * as BaseApi from '@/api/base/base';
import * as workorderApi from '@/api/order/workorder';

export default {
  components: {
  },
  data () {
    return {
		failedBillBoList: [],
		resendContent: '',
		submitResendShow: false,
		selectedBill: {
			selectedBillBatchNo: null,
			sendStatus: null,
		},
		
		accordionVal:'',
		pickedDateRange: [],
        params: {
			pageNum: 0,
			pageSize: 10
		},
		detailLoading: false,
		workOrderList: [],
		allSubMaterialList: [],
		
		pickedMainList: [
		// 	{
		// 	status: 'FINISHED',
		// 	mainText: '10-24（成功：GW0032-072344W）',
		// 	thumb: '/static/picked/success.png',
		// 	contractCode: 'GW0032-072344W',
		// 	fBillNo: '001',
		// 	sendNum: 1,
		// },
		],
		
		contractCode: '',
		
		// 悬浮按钮
		pattern: {
			color: '#7A7E83',
			backgroundColor: '#fff',
			selectedColor: '#007AFF',
			buttonColor: '#007AFF',
			iconColor: '#fff',
			icon: 'gear'
		},
		content: [{
				iconPath: '/static/img/refresh.png',
				selectedIconPath: '/static/img/refresh.png',
				text: '刷新数据',
				active: false
			},{
				iconPath: '/static/picked/resend.png',
				selectedIconPath: '/static/picked/resend_selected.png',
				text: '失败重推',
				active: false
			}
		],
		horizontal: 'left',
		vertical: 'bottom',
		direction: 'vertical',
    }
  },
  created () {
  },
  onLoad(options) {
	  this.pickedDateRange.push(Date.now() - 2*24*3600*1000);
	  this.pickedDateRange.push(Date.now() + 2);
	  
	  console.log("options:", options);
	  
	  if (options.contractCode) {
	  	this.contractCode = decodeURIComponent(options.contractCode);
		this.loadData();
	  }
  },
  methods: {
	formatDateString(timestamp) {
		// 将长整型时间戳转换为毫秒
		const date = new Date(timestamp);
		// 获取年份、月份和日期
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以加1
		const day = String(date.getDate()).padStart(2, '0');
	
		// 返回格式化的日期字符串
		return `${year}-${month}-${day}`;
	},
	pickedDisplay() {
		this.pickedRangeShow = true;
	},
	dateRangeClick(e) {
		this.loadData();
	},
	change(e) {
		if (!e) {
			console.log("关闭");
			this.selectedBill = {
				selectedBillBatchNo: null,
				sendStatus: null,
			};
			return;
		}
		// 通过 this.accordionVal 拿到具体的入库单号，根据入库单号再查询明细数据
		const main = this.pickedMainList[Number(e)];
		
		this.selectedBill = {
			selectedBillBatchNo: main.transferNo,
			sendStatus: main.status,
		};
		this.queryHistoryDetailByTransferNo(main.transferNo);
	},
	queryHistoryDetailByTransferNo(transferNo) {
		const params = {
			transferNo: transferNo,
		};
		// TODO 根据fBillNo 查询推送明细数据
		workorderApi.queryPickedDetail(params).then(res => {
			// console.log("入库详情查询:", res);
			if (res && res.data) {
				this.workOrderList = res.data.pickedBoList || [];
				this.allSubMaterialList = res.data.pickedItemList || [];
				this.failedBillBoList = res.data.failedBillBoList || [];
			} else {
				this.workOrderList = [];
				this.allSubMaterialList = [];
				this.failedBillBoList = [];
			}
		}).catch(err => {
			this.workOrderList = [];
			this.allSubMaterialList = [];
			this.failedBillBoList = [];
			// 提交异常
			console.error("入库详情查询发生异常", err);
			this.$refs.uToast.error(`入库详情查询发生异常！请稍后重试`);
		});
	},
    // 加载入库记录数据
    loadData () {
		if (!this.pickedDateRange || this.pickedDateRange.length != 2) {
			this.$refs.uToast.error(`请先选择记录日期，再进行查询`);
			return;
		}
		const param = {
			startTime: this.formatDateString(this.pickedDateRange[0]),
			endTime: this.formatDateString(this.pickedDateRange[1]),
			contractCode: this.contractCode,
			orderType: "2", // 入库单类型
		};
		console.log("查询条件:", param);
		workorderApi.queryPickedHistory(param).then(res => {
			if (res && res.rows) {
				this.pickedMainList = res.rows || [];
			}
			if (this.selectedBill.selectedBillBatchNo) {
				this.queryHistoryDetailByTransferNo(this.selectedBill.selectedBillBatchNo);
			}
		});
    },
	submitResend() {
		// workorderApi.resendPicked({
		// 	fbillNo: this.selectedBill.selectedBillBatchNo,
		// }).then(res => {
		// 	// console.log("重推失败的入库单结果:", res);
		// 	this.loadData();
		// 	this.submitResendShow = false;
		// 	if (res && res.code === 200) {
		// 		this.selectedBill.sendStatus = "PENDING";
		// 	}
		// }).catch(err => {
		// 	// 提交异常
		// 	console.error("重推失败的入库单发生异常", err);
		// 	this.$refs.uToast.error(`重推失败的入库单发生异常！请稍后重试`);
		// });
	},
    navigateTo (item) {
      if (item && item.id) {
        uni.navigateTo({ url: '/pages/work/dayreport/dutysubmit?id=' + item.id })
      } else {
        uni.navigateTo({ url: '/pages/work/dayreport/dutysubmit' })
      }
    },
	goToPre() {
		console.log("返回主页");
		uni.reLaunch({ url: '/pages/work/index' });
	},
	trigger(e) {
		console.log(e);
		const btn = this.content[e.index];
		btn.active = true;
		if (btn.text === '刷新数据') {
			this.loadData();
		} else if (btn.text === '失败重推') {
			if (!this.selectedBill.selectedBillBatchNo) {
				this.$refs.uToast.error(`您未选择打开一个失败的入库数据，请选择再重推！`);
				return;
			}
			if (this.selectedBill.sendStatus != "FAILED") {
				this.$refs.uToast.error(`只有失败的入库单，才需要再重推！`);
				return;
			}
			this.resendContent = `您确定要重推入库单吗？\n 入库单：${this.selectedBill.selectedBillBatchNo}`;
			this.submitResendShow = true;
		}
	},
	fabClick() {
	},
  }
}
</script>

<style lang="scss" scoped>
.mobile-item-container {
	padding-top: 0px;
}
.list-item {
  padding: 20rpx 0;
  border-bottom: 0.5px solid #ccc;
}

.example-body {
	flex-direction: column;
	flex: 1;
}

.content {
	padding:  5px;
}

.text {
	font-size: 14px;
	color: #666;
	line-height: 20px;
}

.button {
	// margin-top: 10px;
	margin: 10px;
	margin-bottom: 0;
}
</style>